package sdk


import (
	"fmt"
	mqtt "github.com/eclipse/paho.mqtt.golang"
	"os"
)

type Device struct {
	Cli mqtt.Client
	Err error
}

func (d *Device) Init(clientID string) {
	opts := mqtt.NewClientOptions().AddBroker("tcp://127.0.0.1:1883")
	opts.SetUsername("pccc/G3pGPzuWg").SetPassword("MqtMEkuZRz")

	if clientID != "" {
		opts.SetClientID("pccc/G3pGPzuWg"+clientID)
	}else {
		opts.SetClientID("pccc/G3pGPzuWg")
	}
	opts.CleanSession =false

	cli :=  mqtt.NewClient(opts)
	token := cli.Connect()

	fmt.Println(token.Wait())
	//fmt.Println(token.Error())

	/*if  token.Wait() && token.Error() != nil {
		fmt.Println(token.Error())
		d.Err = token.Error()
	}*/

	d.Cli = cli
//	d.UploadData()
}



func (d *Device) Start() {
	if token := d.Cli.Subscribe("go-mqtt/sample", 1, func(client mqtt.Client, msg mqtt.Message) {
		fmt.Printf("TOPIC:%s  ", msg.Topic())
		fmt.Printf("MSG:%s  ", msg.Payload())
		fmt.Println()
	}); token.Wait() && token.Error() != nil {

		fmt.Println(token.Error())
		os.Exit(1)
	}

}

func (d *Device) Stop() {
	d.Cli.Disconnect(250)
}

func (d *Device) UploadData()  {
	topic := "upload_data/iotApp/pqpXQoaWg/mac/9876534321"

	token := d.Cli.Publish(topic,1,false,"this a message test jia")
	if token.Error() != nil {
		panic("send message error")
	}
}
